using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace WebApplication
{
	/// <summary>
    /// Summary description for CGRFormation.
	/// </summary>
	public partial class CGRFormation : System.Web.UI.Page
	{
	
		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.ID = "CGRFormation";
		}
		#endregion

        protected void Page_Load(object sender, System.EventArgs e)
		{
            bool    bCurrentlyOperatingPlayer;
            Game    game = Global.getGame (this);;
			string	sPlayer		= Session["PlayerName"].ToString();
//            bool bPriority = sPlayer == game.CGRFormationPriorityPlayerName;
            bool bPriority = false;
            
            if (sPlayer.Equals (game.CGRFormationPriorityPlayerName))
            {
                bPriority = true;
            }

			// TODO need more work here yet to continue CGR formation
            if (game.CGRFormationPriorityPlayerName == "")	// done with cgr formation questions ?
            {
                PriorityCheckBox.Checked = true;    // JWF  10.29/2007  Turn off auto refresh
                game.FormCGR_Finish();
                Response.Redirect ("OperatingRound2.aspx");
//                Server.Transfer("OperatingRound2.aspx");
            }

			Msg.Text = sPlayer + " is the current player and: " + game.CGRFormationPriorityPlayerName + " is the priority";
			SetTitle(sPlayer);
            Money.Text = sPlayer + " has $" + game.Players[sPlayer].Cash.ToString();
			PriorityCheckBox.Text = sPlayer;
			PriorityCheckBox.Checked = bPriority;
            FillTableWithCompanyInfo();
		}

		private void SetTitle (string sNewTitle)
		{
			HtmlGenericControl title = this.FindControl ("Title") as HtmlGenericControl;

			if (title != null)
				title.InnerText = sNewTitle;
		}

        private void EnableControls(bool bEnable)
        {
            Game    game    = Global.getGame (this);;
            string  sPlayer = Session["PlayerName"].ToString();
            Player  player  = game.Players[sPlayer];

            pbDone.Enabled = ((player.CompaniesActedOn == player.CompaniesOwned) && (sPlayer == game.CGRFormationPriorityPlayerName));	// always until all companies had action 

            PriorityCheckBox.Enabled = false;

            // Disable refresh for the current player's turn.  Client side script will handle turning on/off the refresh.
            if (bEnable)
                PriorityCheckBox.Checked = true;
            else
                PriorityCheckBox.Checked = false;
        }

        private void FillTableWithCompanyInfo()
		{
			Game	game    = Global.getGame (this);;
			string	sPlayer	= Session["PlayerName"].ToString();
            Player  player  = game.Players[sPlayer];
			
			foreach (PublicCompany company in game.PublicCompanies)
			{
				// only check open companies
                if (company.Open)
                {
                    if (company.Owner.Name == sPlayer)
				    {
					    if (company.Loans > 0)
					    {
						    int 		nRow = 0;
						    int			nDeficit;
						    Button		button;
						    TableRow	row;
						    TableCell	cell;
    						
						    nRow++;
						    row = new TableRow();
    						
						    // add company
						    cell = new TableCell();
						    cell.Text = company.Name;
						    row.Cells.Add (cell);

                            // add company trains
                            cell = new TableCell();
                            foreach (Train train in company.Trains)
                            {
                                button = new Button();
                                button.Text = train.Name;
                                button.Enabled = false;
                                cell.Controls.Add(button);
                            }
                            row.Cells.Add(cell);

                            // add company stock price
                            cell = new TableCell();
                            cell.Text = company.StockMarketPosition.Value.ToString();
                            row.Cells.Add(cell);

                            // add company cash
						    cell = new TableCell();
						    cell.Text = company.Cash.ToString();
						    row.Cells.Add (cell);

						    // add company loans
						    cell = new TableCell();
						    cell.Text = company.Loans.ToString();
						    row.Cells.Add (cell);

						    // add company deficit
						    cell = new TableCell();
						    cell.Text = "(" + (company.Loans * 100 - company.Cash).ToString() + ")";
						    row.Cells.Add (cell);

						    nDeficit = company.Loans * 100 - company.Cash;

						    // Keep button
                            cell = new TableCell();
                            
                            button = new Button();
						    button.Text = "Keep";
						    button.Click += new System.EventHandler(this.Keep);
                            button.Enabled = PriorityCheckBox.Checked && company.Owner.Cash >= nDeficit && !company.FoldIntoCGRActedOn;
						    button.CommandName = sPlayer;
						    button.CommandArgument = company.Name;
						    cell.Controls.Add(button);

						    // Fold button
						    button = new Button();
						    button.Text = "Fold";
						    button.Click += new System.EventHandler(this.Fold);
						    button.Enabled = PriorityCheckBox.Checked && !company.FoldIntoCGRActedOn;
						    button.CommandName = sPlayer;
						    button.CommandArgument = company.Name;
						    cell.Controls.Add(button);

						    row.Cells.Add (cell);
						    CompanyTable.Rows.AddAt(nRow, row);
					    }
				    }
                }
            }

            player.CompaniesOwned = CompanyTable.Rows.Count - 1;   // dont count title row
            
            if (sPlayer.Equals (game.CGRFormationPriorityPlayerName))
            {
                EnableControls(true);
            }            
            else
            {
                EnableControls(false);
            }
        }
		

		private void Keep(object sender, System.EventArgs e)
		{
			Game			game	= Global.getGame (this);;
			string			sCompany;
			Button			button	= (Button) sender;
			PublicCompany	company;
            string          sPlayer = Session["PlayerName"].ToString();
            Player          player = game.Players[sPlayer];

			sPlayer		= button.CommandName;
			sCompany	= button.CommandArgument;
			company		= game.PublicCompanies[sCompany];
            company.FoldIntoCGRActedOn = true;

			if (company.Owner.Cash >= company.Loans * 100)
			{
				int	nDeficit	= company.Loans * 100 - company.Cash;
				
				// transfer all cash to bank
				game.Bank	 += company.Cash;
				company.Cash  = 0;
                company.Loans = 0;

                // company owner must make up difference
				company.Owner.Cash	-= nDeficit;
				game.Bank			+= nDeficit;
				
				Msg.Text = sPlayer + " has decided to keep the " + sCompany + " at a cost of $" + nDeficit.ToString();
				game.History.Add (Msg.Text);
			}
			else
			{
                player.CompaniesActedOn++;  // JWF 11.9.2007   Folded companies are acted upon, kept companies are removed from the table.
				company.FoldIntoCGR = true;
//                company.FoldIntoCGRActedOn = true;
                Msg.Text = sPlayer + " has insufficient cash to keep the " + sCompany + ".  It must be folded into the CGR.";
				game.History.Add ("The " + sCompany + " will be folded into the CGR");
			}
            
//            player.CompaniesActedOn++;  JWF 11.9.2007  This throws off the DONE push button enable logic.
//            EnableControls(true);
            this.Server.Transfer ("CGRFormation.aspx");
        }

		private void Fold(object sender, System.EventArgs e)
		{
			Game			game	= Global.getGame (this);;
			string			sCompany;
			Button			button	= (Button) sender;
			PublicCompany	company;
            string          sPlayer = Session["PlayerName"].ToString();
            Player          player  = game.Players[sPlayer];

			sCompany	= button.CommandArgument;
			company		= game.PublicCompanies[sCompany];

			company.FoldIntoCGR = true;
            company.FoldIntoCGRActedOn = true;
            
            Msg.Text = "The " + sCompany + " will be folded into the CGR";
			game.History.Add (Msg.Text);

            player.CompaniesActedOn++;
//            EnableControls(true);
            this.Server.Transfer("CGRFormation.aspx");
        }

		protected void pbDone_Click(object sender, System.EventArgs e)
		{
			GivePriorityToNextPlayer();
		}
		
		private void GivePriorityToNextPlayer()
		{
			int		i = 0;
			Game	game = Global.getGame (this);;
			Player	nextPlayer;

			foreach (Player player in game.Players)
			{
				if (player.Name == game.CGRFormationPriorityPlayerName)
					break;
				else
					i++;
			}

			i++;  // The player with priority is the one after the current one

			if (i < game.Players.Count)
				nextPlayer = (Player) game.Players[i];
			else // back to the first player
				nextPlayer = (Player) game.Players[0];

			if (nextPlayer.Name != game.CGRFormationPlayerName)	// have we come back to first guy again?
				game.CGRFormationPriorityPlayerName = nextPlayer.Name;
			else
				game.CGRFormationPriorityPlayerName = "";

            this.Server.Transfer("CGRFormation.aspx");
		}
	}
}
